import type {
    // 请求
    RequestInterceptorItem,
    RequestInterceptorFn,
    RequestInterceptorFnPromise,
    // 响应
    ResponseInterceptorItem,
    ResponseInterceptorFn,
    ResponseInterceptorFnPromise,
} from "../types/engine.type";

class RequestInterceptor {
    // 拦截器
    handlers: RequestInterceptorItem[];
    constructor() {
        // 要处理的 事件 数组
        this.handlers = [];
    }

    use(middleware: RequestInterceptorItem | RequestInterceptorFn | RequestInterceptorFnPromise) {
        if (typeof middleware === "function") {
            let item: RequestInterceptorItem = {
                name: "",
                handler: middleware,
            };
            this.handlers.push(item);
        } else {
            let item = middleware;
            this.handlers.push(item);
        }
    }
    /**
     * 迭代调用
     * @param {Function} fn 迭代要调用的方法
     */
    forEach(fn: (i: RequestInterceptorItem) => void) {
        if (fn === null || typeof fn === "undefined" || typeof fn !== "function") {
            return;
        }
        this.handlers.forEach((item) => {
            fn(item);
        });
    }
}
class ResponseInterceptor {
    // 拦截器
    handlers: ResponseInterceptorItem[];
    constructor() {
        // 要处理的 事件 数组
        this.handlers = [];
    }

    use(
        middleware: ResponseInterceptorItem | ResponseInterceptorFn | ResponseInterceptorFnPromise
    ) {
        if (typeof middleware === "function") {
            let item: ResponseInterceptorItem = {
                name: "",
                handler: middleware,
            };
            this.handlers.push(item);
        } else {
            let item = middleware;
            this.handlers.push(item);
        }
    }
    /**
     * 迭代调用
     * @param {Function} fn 迭代要调用的方法
     */
    forEach(fn: (i: ResponseInterceptorItem) => void) {
        if (fn === null || typeof fn === "undefined" || typeof fn !== "function") {
            return;
        }
        this.handlers.forEach((item) => {
            fn(item);
        });
    }
}

export { RequestInterceptor, ResponseInterceptor };
